<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/5/21
 * Time: 13:24
 */

namespace corephp\db;


use corephp\App;
use corephp\db\query\Query;

class Model extends Query
{
    public function dbConfig()
    {
        $packages = App::config()->get('packages');
        return $packages['db'];
    }

    /**
     * @return \corephp\db\connect\Medoo
     */
    final public function db()
    {
        return App::singleObject($this->dbConfig());
    }

    public function select()
    {
        $where = $this->where;
        if($this->orderBy){
            $where['ORDER'] = $this->orderBy;
        }
        if($this->limit){
            $where['LIMIT'] = $this->limit;
        }
        return is_null($this->join) ? $this->db()->select($this->table, $this->field, $where) : $this->db()->select($this->table, $this->join, $this->field, $where);
    }

    public function insert()
    {
        return $this->db()->insert($this->table,$this->data);
    }

    public function update()
    {
        return $this->db()->update($this->table,$this->data,$this->where);
    }

    public function delete()
    {
        return $this->db()->delete($this->table,$this->where);
    }

    public function replace()
    {

    }

    public function get()
    {
        $where = $this->where;
        if(!is_null($this->orderBy)){
            $where['ORDER'] = $this->orderBy;
        }
        return is_null($this->join) ? $this->db()->get($this->table,$this->field,$where) : $this->db()->get($this->table,$this->join,$this->field,$where);
    }

    public function has()
    {
        return is_null($this->join) ? $this->db()->has($this->table,$this->where):$this->db()->has($this->table,$this->join,$this->where);

    }

    public function count()
    {
        return is_null($this->join) ? $this->db()->count($this->table,$this->field,$this->where):$this->db()->count($this->table,$this->join,$this->field,$this->where);
    }

    public function max()
    {
        return is_null($this->join) ? $this->db()->max($this->table,$this->field,$this->where):$this->db()->max($this->table,$this->join,$this->field,$this->where);

    }

    public function min()
    {
        return is_null($this->join) ? $this->db()->min($this->table,$this->field,$this->where):$this->db()->min($this->table,$this->join,$this->field,$this->where);
    }

    public function avg()
    {
        return is_null($this->join) ? $this->db()->avg($this->table,$this->field,$this->where):$this->db()->avg($this->table,$this->join,$this->field,$this->where);
    }

    public function sum()
    {
        return is_null($this->join) ? $this->db()->sum($this->table,$this->field,$this->where):$this->db()->sum($this->table,$this->join,$this->field,$this->where);
    }
}